<template>
  <el-dialog v-model="props.distVisible" title="角色权限分配" :width="mobile ? '80%' : '40%'" draggable
             :before-close="closeDialog">
    <el-row>
      <el-col :lg="24" style="max-height:400px;overflow: auto;">
        <el-tree ref="treeRef" :data="treeData" show-checkbox default-expand-all node-key="id" highlight-current
                 :props="defaultProps" check-strictly :default-checked-keys="chooseData"/>
      </el-col>
    </el-row>
    <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="handleSave()" :loading="loading">保存</el-button>
                <el-button @click="closeDialog">
                    关闭
                </el-button>
            </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {reactive, ref, onBeforeMount, watch} from 'vue'
import {ElMessage} from 'element-plus';
import {getMenuList} from '@/api/menu/index'
import {roleMenuTreeInsert, findAllRoleIdChoose} from '@/api/system/role'

const props = defineProps({
  distVisible: Boolean,
  mobile: Boolean
})
let currentRoleId = ref(null)
let treeData = ref([])
let chooseData = ref([])
let treeRef = ref(null)
const defaultProps = {
  children: 'children',
  label: 'name',
}

const emit = defineEmits(['distCloseDialog'])
const closeDialog = () => {
  treeRef.value.setCheckedKeys([], false)
  emit('distCloseDialog')
}

const getTreeList = async () => {
  let res = await getMenuList();
  console.log('getTreeList', res)
  treeData.value = res.data.list
}


const findCurrent = async (roleId) => {
  currentRoleId.value = roleId.id
  let res = await findAllRoleIdChoose({role_id: roleId.id})
  treeRef.value.setCheckedKeys(res.data, false)
  chooseData = res.data
  console.log('findAllRoleIdChoose', res)
}


let loading = ref(false)
const handleSave = async () => {
  console.log(treeRef.value.getCheckedKeys(false))
  let obj = {
    role_id: currentRoleId.value,
    menu_id: treeRef.value!.getCheckedKeys(false)
  }
  console.log(obj)
  loading.value = true
  let res = await roleMenuTreeInsert(obj)
  loading.value = false
  if (res) {
    ElMessage({message: '操作成功', type: 'success'})
    closeDialog()
  }
}

watch(() => props.distVisible, (newValue) => {
  if (newValue) {
    getTreeList()
  }
}, {deep: true, immediate: true})

defineExpose({
  findCurrent
})
</script>
<style scoped></style>